#include "auth.h"
#include "../utils/axios.h"

user_t current_user;

cJSON *auth_json(int id, const char *username) {
    cJSON *auth = cJSON_CreateObject();
    cJSON_AddNumberToObject(auth, "id", id);
    cJSON_AddStringToObject(auth, "username", username);
    return auth;
}

response_t *auth_login(char *username, char *password) {
    cJSON *data = cJSON_CreateObject();
    cJSON_AddStringToObject(data, "username", username);
    cJSON_AddStringToObject(data, "password", password);
    log_debug("request login");
    response_t *response = request(MEVEN_HTTP_POST, "/auth/login", NULL, data);
    if (response->code == RESPONSE_OK) {

        cJSON *body = response->body;

        int id = cJSON_GetObjectItem(body, "id")->valueint;

        current_user.id = id;
        log_info("%d", id);
        strcpy(current_user.username, username);
        log_info("auth_login id: %d username: %s", id, username);
        return response;
    } else {
        return response;
    }
}

response_t *auth_logout(int user_id) {
    cJSON *data = cJSON_CreateObject();
    cJSON_AddStringToObject(data, "user_id", user_id);
    response_t *response = request(MEVEN_HTTP_POST, "/auth/logout", NULL, data);
    cJSON_Delete(data);
    return response;
}

response_t *auth_register(char *username, char *password) {
    cJSON *data = cJSON_CreateObject();
    cJSON_AddStringToObject(data, "username", username);
    cJSON_AddStringToObject(data, "password", password);
    response_t *response =
        request(MEVEN_HTTP_POST, "/auth/register", NULL, data);
    cJSON_Delete(data);
    return response;
}